OUTPUT_BACKGROUND="white"
OUTPUT_SIZE="400x230"
LOGO_TRIM_FUZZ=0
LOGO_HEIGHT_TOLERANCE=10
LOGO_DESIRED_HEIGHT=85
LOGO_DESIRED_WIDTH=230

WORKDIR=$(mktemp -d -t stdlogo-XXXX)


calc() { awk "BEGIN{print int($*)}"; }


cp $1/* $WORKDIR/

for f in $WORKDIR/*.svg; do
    convert $f ${f%.svg}.png
    rm $f
done

for f in $WORKDIR/*.png; do
    convert $f -background $OUTPUT_BACKGROUND -flatten -alpha off ${f%.png}.jpg
    rm $f
done


for f in $WORKDIR/*.jpg; do
    mogrify $f -fuzz "${LOGO_TRIM_FUZZ}%" -trim  +repage $f
    width=$(identify -format '%w' $f)
    height=$(identify -format '%h' $f)
    scaled_height=$(calc "($LOGO_DESIRED_WIDTH/$width)*$height")
    if [ "$scaled_height" -lt "$(calc $LOGO_DESIRED_HEIGHT + $LOGO_HEIGHT_TOLERANCE)" ];
        then 
            mogrify $f -geometry "${LOGO_DESIRED_WIDTH}x" -gravity center -background $OUTPUT_BACKGROUND -extent $OUTPUT_SIZE $f
        else
            mogrify $f -geometry "x${LOGO_DESIRED_HEIGHT}" -gravity center -background $OUTPUT_BACKGROUND -extent $OUTPUT_SIZE $f
    fi;

done 

for f in $WORKDIR/*.jpg; do
    convert $f ${f%.jpg}.png
    rm $f
done

[ ! -d "$2" ] && mkdir -p $2

mv $WORKDIR/* $2/

rm -rf $WORKDIR
